import React, { Component } from 'react';
import { Message, Dialog, Button, Grid, Table, Pagination, Tag, Transfer } from '@alifd/next';
import IceContainer from '@icedesign/container';
import IceLabel from '@icedesign/label';
import axios from 'axios';
import { assign, authorizedUser } from '../../../../api/Role';
import { page } from '../../../../api/User';
import '../RoleTable.scss';
import eventProxy from '../../../../libs/eventProxy';

const { Group: TagGroup, Closeable: CloseableTag } = Tag;

export default class AssignDialog2 extends Component {
  static displayName = 'AssignDialog';

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
      sourceData: [],
      offset: 0,
      limit: 10,
      total: 10,
      visible: false,
    };
    this.handData = {
      added: [],
      deleted: [],
    };
    this.onChangePage = this.onChangePage.bind(this);
  }

  componentWillMount() {
    this.oth_fields = {
      roleType: '1',
    };
  }

  updateTable(offset, limit) {
    page({
      offset: offset,
      limit: limit,
    }).then((response) => {
      const data = response.data.data;
      const source = this.dataToShow(data.rows);
      authorizedUser({ id: this.props.record.id }).then(resp2 => {
        const authList = resp2.data.data;
        const authedData = [];
        authList.forEach(ele => {
          authedData.push(`${ele.id}`);
        });
        this.setState({
          visible: true,
          sourceData: source,
          authed: authedData,
          total: data.count,
        });
      });
    });
  }

  dataToShow = (data) => {
    const source = [];
    data.forEach(element => {
      source.push({
        label: `${element.name}(${element.loginName})`,
        value: `${element.id}`,
      });
    });
    return source;
  }
  handleSubmit = () => {
    const values = new URLSearchParams();
    const added = this.handData.added.filter(v => !this.handData.deleted.includes(v));
    const deled = this.handData.deleted.filter(v => !this.handData.added.includes(v));
    values.append('addIds', added.join(','));
    values.append('delIds', deled.join(','));
    values.append('roleId', this.props.record.id);
    assign(values).then((response) => {
      const data = response.data;
      if (data.code === 200) {
        Message.success('操作成功');
        this.setState({
          visible: false,
        });
      } else {
        Message.warning('操作失败');
      }
    });
  };

  onOpen = () => {
    this.handData = {
      added: [],
      deleted: [],
    };
    this.updateTable(this.state.offset, this.state.limit);
  };

  onClose = () => {
    this.setState({
      visible: false,
    });
  };
  handleChange = (value, data, extra) => {
    const direction = extra.direction;
    if (direction === 'right') {
      this.handData.added = this.handData.added.concat(extra.movedValue);
    } else if (direction === 'left') {
      this.handData.deleted = this.handData.deleted.concat(extra.movedValue);
    }
  }
  onChangePage = (cur) => {
    const offset = (cur - 1) * this.state.limit;
    this.updateTable(offset, this.state.limit);
    this.setState({
      offset: offset, 
    });
  }
  render() {
    const { Row, Col } = Grid;
    const roleName = this.props.record.name;
    return (
      <div style={styles.editDialog}>
        <Button type="primary" size="small" onClick={this.onOpen}>
        角色分配
        </Button>
        <Dialog
          style={{ width: 840 }}
          visible={this.state.visible}
          onOk={this.handleSubmit}
          closeable="esc,mask,close"
          onCancel={this.onClose}
          onClose={this.onClose}
          title="分配"
        >
          <IceContainer>
            <Row align="center" gutter="6" style={styles.rows}>
              <Col span="6" >
                <IceLabel style={{ color: '#fdd8e7', fontSize: '16px' }}> 角色：{roleName}</IceLabel>
              </Col>
            </Row>
            <Row align="center" justify="center" gutter="6">
              <Col span="24">
                <Transfer
                    showSearch 
                    defaultValue={this.state.authed} 
                    dataSource={this.state.sourceData} 
                    onChange={this.handleChange} 
                    titles={['未分配该角色', '已分配该角色']} 
                />
              </Col>
            </Row>
            <Row>
              <Col span="3" offset="2">
                <Pagination size="medium" shape="no-border" type="simple" onChange={this.onChangePage} pageSize={this.state.limit} total={this.state.total} className="paging" />
              </Col>
            </Row>
          </IceContainer>
        </Dialog>
      </div>
    );
  }
}

const styles = {
  editDialog: {
    display: 'inline-block',
    marginRight: '5px',
  },
  rows: {
    marginBottom: '20px',
  },
};
